//
//  LSPolicyLawsViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2018/12/26.
//  Copyright © 2018 wpkj. All rights reserved.
//

#import "LSPolicyLawsViewController.h"
#import "LSDatePickViewController.h"
#import "LSPolicyLawsTableViewCell.h"
#import "LSNewsViewModel.h"
#import "LSNewsDetailViewController.h"

@interface LSPolicyLawsViewController () <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITextField *searchInfoTF;
@property (nonatomic, strong) UITextField *timeSelectBeginnerTF;
@property (nonatomic, strong) UITextField *timeSelectFinisherTF;
@property (nonatomic, strong) UITableView *policyLawsTableView;
@property (nonatomic, strong) NSMutableArray *dataArrayM;
@end

static NSString *LSPolicyLawsTableViewCellID = @"LSPolicyLawsTableViewCellID";

@implementation LSPolicyLawsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"政策解读";
//    [self setUpHeaderView];
    [self.view addSubview:self.policyLawsTableView];
    self.policyLawsTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self loadData];
}

- (void)setUpHeaderView {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 70)];
    headerView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:headerView];
    UIView *headerViewBottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 69.5, ScreenWidth, 0.5)];
    headerViewBottomLineView.backgroundColor = hexColor(CCCCCC);
    [headerView addSubview:headerViewBottomLineView];
    UITextField *searchInfoTF = [[UITextField alloc] initWithFrame:CGRectMake((ScreenWidth-310)/2, 8, 310, 24)];
    self.searchInfoTF = searchInfoTF;
    searchInfoTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12];
    searchInfoTF.layer.borderColor = hexColor(dbdbdb).CGColor;
    searchInfoTF.layer.borderWidth = 1;
    searchInfoTF.returnKeyType = UIReturnKeySearch;
    searchInfoTF.placeholder = @"请输入您要查找的内容";
    searchInfoTF.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 1)];
    searchInfoTF.leftViewMode = UITextFieldViewModeAlways;
    [headerView addSubview:searchInfoTF];
    UILabel *timeSelectTipLabel = [[UILabel alloc] initWithFrame:CGRectMake((ScreenWidth-310)/2, 30, 38, 40) andText:@"时间:" andTextColor:hexColor(666666) andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:12] andTextAlignment:NSTextAlignmentLeft];
    [headerView addSubview:timeSelectTipLabel];
    UITextField *timeSelectBeginnerTF = [[UITextField alloc] initWithFrame:CGRectMake((ScreenWidth-310)/2+38, 40, 90, 20)];
    self.timeSelectBeginnerTF = timeSelectBeginnerTF;
    timeSelectBeginnerTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:11];
    timeSelectBeginnerTF.delegate = self;
    timeSelectBeginnerTF.layer.borderColor = hexColor(dbdbdb).CGColor;
    timeSelectBeginnerTF.layer.borderWidth = 0.5;
    timeSelectBeginnerTF.backgroundColor = hexColor(EEEEEE);
    UIImageView *timeSelectBeginnerTFRightViewImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    timeSelectBeginnerTFRightViewImageView.image = [UIImage imageNamed:@"xiala"];
    timeSelectBeginnerTF.rightView = timeSelectBeginnerTFRightViewImageView;
    timeSelectBeginnerTF.rightViewMode = UITextFieldViewModeAlways;
    [headerView addSubview:timeSelectBeginnerTF];
    UILabel *zhiLabel = [[UILabel alloc] initWithFrame:CGRectMake((ScreenWidth-310)/2+38+90, 30, 15, 40) andText:@"至" andTextColor:hexColor(666666) andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:12] andTextAlignment:NSTextAlignmentCenter];
    [headerView addSubview:zhiLabel];
    UITextField *timeSelectFinisherTF = [[UITextField alloc] initWithFrame:CGRectMake((ScreenWidth-310)/2+38+90+15, 40, 90, 20)];
    self.timeSelectFinisherTF = timeSelectFinisherTF;
    timeSelectFinisherTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:11];
    timeSelectFinisherTF.delegate = self;
    timeSelectFinisherTF.layer.borderColor = hexColor(dbdbdb).CGColor;
    timeSelectFinisherTF.layer.borderWidth = 0.5;
    timeSelectFinisherTF.backgroundColor = hexColor(EEEEEE);
    UIImageView *timeSelectFinisherTFRightViewImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    timeSelectFinisherTFRightViewImageView.image = [UIImage imageNamed:@"xiala"];
    timeSelectFinisherTF.rightView = timeSelectFinisherTFRightViewImageView;
    timeSelectFinisherTF.rightViewMode = UITextFieldViewModeAlways;
    [headerView addSubview:timeSelectFinisherTF];
    UIButton *searchButton = [[UIButton alloc] initWithFrame:CGRectMake((ScreenWidth-310)/2+38+90+15+90+20, 40, 54, 20)];
    searchButton.backgroundColor = NAV_COLOR;
    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    [searchButton setTitleColor:hexColor(f7f7f7) forState:UIControlStateNormal];
    searchButton.layer.cornerRadius = 3;
    searchButton.layer.masksToBounds = true;
    searchButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:10];
    [searchButton addTarget:self action:@selector(searchButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:searchButton];
}

#pragma mark - 搜索按钮点击事件
- (void)searchButtonClick {
    [MBProgressHUD showTipMessageInWindow:@"搜索"];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == self.timeSelectBeginnerTF) {// 搜索开始时间段
        LSDatePickViewController *alertVC = [LSDatePickViewController alertControllerWithTitle:@"设置开始时间\n\n\n\n\n\n\n\n\n" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 获取当前datePicker上面选择的时间
            NSDate *date = alertVC.datePicker.date;
            //    NSLog(@"-----%@", date);
            // 创建时间格式化工具
            NSDateFormatter *df = [[NSDateFormatter alloc] init];
            df.dateFormat = @"yyyy-MM-dd";
            NSString *str = [df stringFromDate:date];
            self.timeSelectBeginnerTF.text = [NSString stringWithFormat:@"    %@",str];
            self.timeSelectBeginnerTF.backgroundColor = UIColor.whiteColor;
        }];
        [alertVC addAction:cancelAction];
        [alertVC addAction:okAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    } else {// 搜索结束时间段
        LSDatePickViewController *alertVC = [LSDatePickViewController alertControllerWithTitle:@"设置开始时间\n\n\n\n\n\n\n\n\n" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 获取当前datePicker上面选择的时间
            NSDate *date = alertVC.datePicker.date;
            //    NSLog(@"-----%@", date);
            // 创建时间格式化工具
            NSDateFormatter *df = [[NSDateFormatter alloc] init];
            df.dateFormat = @"yyyy-MM-dd";
            NSString *str = [df stringFromDate:date];
            self.timeSelectFinisherTF.text = [NSString stringWithFormat:@"    %@",str];
            self.timeSelectFinisherTF.backgroundColor = UIColor.whiteColor;
        }];
        [alertVC addAction:cancelAction];
        [alertVC addAction:okAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
    return false;
}

- (void)loadData {
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:PolicyLawsList param:@{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"pageNo":@"1",@"count":@"100"} completionHandler:^(id responseObject, NSError *connectionError) {
        [self.policyLawsTableView.mj_header endRefreshing];
        if (!connectionError) {
            NSLog(@"返回数据----%@",responseObject);
            NSNumber *status = [responseObject objectForKey:@"status"];
            if (status.integerValue == 200) {
                [self.dataArrayM removeAllObjects];
                NSArray *dataArray = [responseObject objectForKey:@"data"];
                if (dataArray > 0) {
                    for (NSDictionary *dict in dataArray) {
                        LSNewsViewModel *model = [LSNewsViewModel mj_objectWithKeyValues:dict];
                        if (model) {
                            [self.dataArrayM addObject:model];
                        }
                    }
                    [self.policyLawsTableView reloadData];
                }
            }
        } else {
            [MBProgressHUD showTipMessageInWindow:[NSString stringWithFormat:@"%@",connectionError.localizedDescription]];
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArrayM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSPolicyLawsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LSPolicyLawsTableViewCellID forIndexPath:indexPath];
    LSNewsViewModel *model = self.dataArrayM[indexPath.row];
    cell.mainTitleText = model.title;
    // iOS 生成的时间戳是10位
    NSTimeInterval interval = [model.releaseDate doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateString = [formatter stringFromDate: date];
    cell.timeText = dateString;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    LSNewsViewModel *model = self.dataArrayM[indexPath.row];
    LSNewsDetailViewController *newsDetailVC = [[LSNewsDetailViewController alloc] init];
    newsDetailVC.newsDetailID = model.id;
    [self.navigationController pushViewController:newsDetailVC animated:true];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return LSPolicyLawsTableViewCellHeight;
}

- (UITableView *)policyLawsTableView {
    if (!_policyLawsTableView) {
        _policyLawsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight)];
        _policyLawsTableView.backgroundColor = hexColor(EEEEEE);
        _policyLawsTableView.separatorInset = UIEdgeInsetsMake(0, ScreenWidth, 0, 0);
        _policyLawsTableView.delegate = self;
        _policyLawsTableView.dataSource = self;
        _policyLawsTableView.tableFooterView = [UIView new];
        [_policyLawsTableView registerClass:LSPolicyLawsTableViewCell.class forCellReuseIdentifier:LSPolicyLawsTableViewCellID];
    }
    return _policyLawsTableView;
}

- (NSMutableArray *)dataArrayM {
    if (!_dataArrayM) {
        _dataArrayM = [[NSMutableArray alloc] init];
    }
    return _dataArrayM;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
